<template>
  <div class="player-container">
    <template v-if="hlsurl">
      <div id="video-content">
        <video
          :id="'myvideo'+cameraId"
          class="video-js vjs-default-skin"
          controls
          preload="auto"
          poster
        >
          <source
            :src="hlsurl"
            type="application/x-mpegURL"
          >
        </video>
      </div>
    </template>
    <template v-if="!hlsurl">
      <img src="@/assets/404_images/404.png" /><span>该设备暂无数据</span>
    </template>
  </div>
</template>

<script>
import videojs from 'video.js'
import 'video.js/dist/video-js.css' // video.js样式
import 'videojs-contrib-hls'

export default {
  props: {
    hlsurl: ,
    cameraId: ,
    isChangeType: false
  },
  data() {
    return {
      videoUrl: '',
      videoId: '',
      videoType: '',
      videoPlayer: null,
      isVideoTypeChange: 0
    }
  },
  watch: {
    hlsurl: {
      immediate: true,
      handler(val) {
        this.videoUrl = val
      }
    },
    cameraId: {
      immediate: true,
      handler(val) {
        this.videoId = val
      }
    },
    isChangeType: {
      immediate: true,
      handler(val) {
        this.isVideoTypeChange = val
      }
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.$watch(function() {
        return { url: this.videoUrl, id: this.videoId, type: this.videoType }
      }, function(params) {
        if (this.videoUrl) {
          if (this.videoPlayer) {
            this.videoPlayer.pause()
            this.videoPlayer.dispose()
            var videoContent = document.getElementById('video-content')
            videoContent.innerHTML = " <video id='myvideo" + this.videoId + "' \
                                            class='video-js vjs-default-skin' \
                                        controls \
                                        preload='auto' \
                                        poster> \
                                        <source \
                                            src='" + this.videoUrl + "' \
                                            type='application/x-mpegURL'> \
                                      </video>"
            var id = 'myvideo' + this.videoId
            this.getVideo(id)
          } else {
            var id = 'myvideo' + this.videoId
            this.getVideo(id)
          }
        }
      })
    })
    var id = 'myvideo' + this.videoId
    this.getVideo(id)
  },
  beforeDestroy: function() {
    this.videoPlayer.dispose()
  },
  methods: {
    getVideo(id) {
      this.videoPlayer = videojs(id, {
        bigPlayButton: true,
        textTrackDisplay: false,
        posterImage: true,
        errorDisplay: false,
        controlBar: true
      }, function() {
        // this.play()
      })
    }
  }
}

</script>

<style lang="scss" scoped>

</style>

